from django.db import models
from utils.models import BaseModel
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,BadData,BadSignature,SignatureExpired
from django.conf import settings

class OAuthQQUser(BaseModel):
    """
    QQ登录用户数据
    """
    # users.User
    # 如果 只写 User 它会在本子应用找User
    user = models.ForeignKey('users.User', on_delete=models.CASCADE, verbose_name='用户')
    openid = models.CharField(max_length=64, verbose_name='openid', db_index=True)

    class Meta:
        db_table = 'tb_oauth_qq'
        verbose_name = 'QQ登录用户数据'
        verbose_name_plural = verbose_name




    @staticmethod
    def generic_token_by_openid(openid):

        #1.创建序列化器
        serializer = Serializer(settings.SECRET_KEY,3600)
        #2.对数据进行编码
        token = serializer.dumps({'openid':openid})
        # token是bytes类型
        return token.decode()


    @staticmethod
    def openid_by_token(token):
        # 1.创建序列化器
        serializer = Serializer(settings.SECRET_KEY, 3600)
        #2. 验证数据
        try:
            result = serializer.loads(token)
            #BadSignature:   被破坏了
            #SignatureExpired: 过期了
        except BadData:
            return None
        else:
            return result.get('openid')




